package com.dataconver.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import java.util.Map;

/**
 * 配置管理器（向后兼容）
 * 负责加载和管理配置，与Spring Boot配置属性类配合使用
 */
@Component
public class ConfigManager {
    private static final Logger logger = LoggerFactory.getLogger(ConfigManager.class);
    
    private static DataSyncProperties dataSyncProperties;
    private static DatabaseProperties databaseProperties;
    
    @Autowired
    private DataSyncProperties syncProps;
    
    @Autowired
    private DatabaseProperties dbProps;
    
    @PostConstruct
    public void init() {
        dataSyncProperties = syncProps;
        databaseProperties = dbProps;

    }
    
    /**
     * 获取字符串配置值
     */
    public static String getString(String key, String defaultValue) {
        try {
            Object value = getNestedValue(key, Object.class);
            return value != null ? value.toString() : defaultValue;
        } catch (Exception e) {
            return defaultValue;
        }
    }
    
    /**
     * 获取整数配置值
     */
    public static int getInt(String key, int defaultValue) {
        try {
            Object value = getNestedValue(key, Object.class);
            if (value instanceof Number) {
                return ((Number) value).intValue();
            }
            return Integer.parseInt(value.toString());
        } catch (Exception e) {
            return defaultValue;
        }
    }
    
    /**
     * 获取布尔配置值
     */
    public static boolean getBoolean(String key, boolean defaultValue) {
        try {
            Object value = getNestedValue(key, Object.class);
            if (value instanceof Boolean) {
                return (Boolean) value;
            }
            return Boolean.parseBoolean(value.toString());
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * 获取Map配置值（嵌套）
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> getMap(String key) {
        Object value = getNestedValue(key, Object.class);
        if (value instanceof Map) {
            return (Map<String, Object>) value;
        }
        return null;
    }
    
    /**
     * 获取嵌套配置值
     */
    @SuppressWarnings("unchecked")
    public static <T> T getNestedValue(String key, Class<T> type) {
        String[] keys = key.split("\\.");
        
        // 处理数据库配置
        if (keys[0].equals("sqlserver") || keys[0].equals("mysql")) {
            return getDatabaseValue(keys, type);
        }
        
        // 处理同步配置
        if (keys[0].equals("sync")) {
            return getSyncValue(keys, type);
        }
        
        return null;
    }
    
    /**
     * 获取数据库配置值
     */
    @SuppressWarnings("unchecked")
    private static <T> T getDatabaseValue(String[] keys, Class<T> type) {
        if (databaseProperties == null) return null;
        
        try {
            if (keys[0].equals("sqlserver")) {
                if (keys.length == 2) {
                    switch (keys[1]) {
                        case "url": return (T) databaseProperties.getSqlserver().getUrl();
                        case "username": return (T) databaseProperties.getSqlserver().getUsername();
                        case "password": return (T) databaseProperties.getSqlserver().getPassword();
                        case "driver": return (T) databaseProperties.getSqlserver().getDriver();
                        case "maxPoolSize": return (T) Integer.valueOf(databaseProperties.getSqlserver().getMaxPoolSize());
                        case "minIdle": return (T) Integer.valueOf(databaseProperties.getSqlserver().getMinIdle());
                    }
                }
            } else if (keys[0].equals("mysql")) {
                if (keys.length == 2) {
                    switch (keys[1]) {
                        case "url": return (T) databaseProperties.getMysql().getUrl();
                        case "username": return (T) databaseProperties.getMysql().getUsername();
                        case "password": return (T) databaseProperties.getMysql().getPassword();
                        case "driver": return (T) databaseProperties.getMysql().getDriver();
                        case "maxPoolSize": return (T) Integer.valueOf(databaseProperties.getMysql().getMaxPoolSize());
                        case "minIdle": return (T) Integer.valueOf(databaseProperties.getMysql().getMinIdle());
                    }
                }
            }
        } catch (Exception e) {
            // 配置获取失败，返回null
        }
        
        return null;
    }
    
    /**
     * 获取同步配置值
     */
    @SuppressWarnings("unchecked")
    private static <T> T getSyncValue(String[] keys, Class<T> type) {
        if (dataSyncProperties == null) return null;
        
        try {
            if (keys.length == 2) {
                switch (keys[1]) {
                    case "cron": return (T) dataSyncProperties.getCron();
                    case "batchSize": return (T) Integer.valueOf(dataSyncProperties.getBatchSize());
                    case "maxRetries": return (T) Integer.valueOf(dataSyncProperties.getMaxRetries());
                    case "retryDelay": return (T) Integer.valueOf(dataSyncProperties.getRetryDelay());
                }
            } else if (keys.length == 3 && keys[1].equals("table")) {
                String tableName = keys[2];
                DataSyncProperties.TableConfig tableConfig = dataSyncProperties.getTable().get(tableName);
                if (tableConfig != null) {
                    return (T) tableConfig;
                }
            } else if (keys.length == 4 && keys[1].equals("table")) {
                String tableName = keys[2];
                String property = keys[3];
                DataSyncProperties.TableConfig tableConfig = dataSyncProperties.getTable().get(tableName);
                if (tableConfig != null) {
                    switch (property) {
                        case "enabled": return (T) Boolean.valueOf(tableConfig.isEnabled());
                        case "source": return (T) tableConfig.getSource();
                        case "key": return (T) tableConfig.getKey();
                        case "strategy": return (T) tableConfig.getStrategy();
                        case "timestamp": return (T) tableConfig.getTimestamp();
                        case "columnMapping": return (T) tableConfig.getColumnMapping();
                    }
                }
            }
        } catch (Exception e) {
            // 配置获取失败，返回null
        }
        
        return null;
    }
}
